/*
 * Copyright (c) 2011 Metrum Research Group LLC. All Rights Reserved.
 *
 * You may use this software under the terms of GPL v3 (http://www.gnu.org/licenses/gpl.html).
 *
 * METRUM RESEARCH GROUP LLC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. METRUM RESEARCH GROUP LLC SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package sumo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;
import com.sshtools.j2ssh.connection.ChannelState;

public class SetupSessionServlet extends HttpServlet { 
	private static final long serialVersionUID = 1L;
	//private static long limitToPrompt = SumoPropertyManager.getConfig().getLong("connection.timeLimitToPrompt");
	
	public void doPost(HttpServletRequest req, HttpServletResponse res){	
		try {
			// If user hasn't been set up with a session...
			HttpSession theSession = req.getSession();
			boolean Prompt = true;
			if(theSession.getAttribute("SESSION") == null)Prompt = setupSession(req, theSession);
			if(Prompt)getServletConfig().getServletContext().getRequestDispatcher("/evaluate.jsp").forward(req, res);
			else getServletConfig().getServletContext().getRequestDispatcher("/logout.jsp").forward(req, res);	
		}catch (InterruptedException ie){
			ie.printStackTrace();
		}catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private boolean setupSession(
		HttpServletRequest req, 
		HttpSession theSession
	)throws IOException, InterruptedException {
		String host = SumoPropertyManager.getConfig().getString("connection.host");	
		String command = SumoPropertyManager.getConfig().getString("connection.command");
		String username = req.getParameter("username");
		String password = req.getParameter("password"); 
		SshClient ssh = new SshClient();
		ssh.connect(host, new IgnoreHostKeyVerification());
		PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
		pwd.setUsername(username);
		pwd.setPassword(password);
		int result = ssh.authenticate(pwd);
		if(result!=AuthenticationProtocolState.COMPLETE) return false;
		SessionChannelClient session = ssh.openSessionChannel();//not to be confused with "theSession"
		if(!(session.requestPseudoTerminal("ansi",80,24,0,0,""))) return false;
		boolean success = session.executeCommand(command);			
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		IOUtil iou = new IOUtil();
		iou.readWrite(session.getInputStream(), baos);	
		OutputStream os = session.getOutputStream();
		ExpressionEvaluator R = new ExpressionEvaluator();
		R.setRInputStream(session.getInputStream());
		R.setROutputStream(os);
		R.setROutput(baos);
		theSession.setAttribute("connection",ssh);
		theSession.setAttribute("SESSION", session);
		theSession.setAttribute("SESSION_OUTPUT_STREAM", os);  	
		theSession.setAttribute("Output", baos);
		theSession.setAttribute("SESSION_INPUT_STREAM", session.getInputStream());   	
		theSession.setAttribute("username", username);
		theSession.setAttribute("evaluator",R);
		return true;
			
	}
}